package com.suke.czx.modules.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.Constant;
import com.suke.czx.common.utils.FieldConstant;
import com.suke.czx.common.utils.R;
import com.suke.czx.common.validate.SysRoleSaveGroup;
import com.suke.czx.common.validate.SysRoleUpdateGroup;
import com.suke.czx.modules.sys.entity.SysRole;
import com.suke.czx.modules.sys.entity.SysRoleMenu;
import com.suke.czx.modules.sys.service.SysRoleMenuService;
import com.suke.czx.modules.sys.service.SysRoleService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 应用模块名称: 角色
 * 代码描述: 角色控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/08/27 16:31
 */
@Validated
@RestController
@RequestMapping("/api/role")
@AllArgsConstructor
@Api(value = "SysRoleController", tags = "角色管理")
public class SysRoleController extends AbstractController {

	private final SysRoleService sysRoleService;

	private final SysRoleMenuService sysRoleMenuService;

	/**
	 * 分页查询角色列表
	 * @param params 查询参数
	 * @return VO
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@PreAuthorize("hasRole('but:role:list')")
	public R list(@RequestParam Map<String, Object> params) {
		if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
			return R.error("缺少分页信息");
		}
		// 查询列表数据
		QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne(StrUtil.toUnderlineCase(FieldConstant.ROLE_NAME), Constant.SUPER_ADMIN_NAME);
		if (params.size() > 2) {
			queryWrapper.like(!StrUtil.isBlankIfStr(params.get(FieldConstant.ROLE_NAME)), StrUtil.toUnderlineCase(FieldConstant.ROLE_NAME), params.get(FieldConstant.ROLE_NAME));
		}
		IPage<SysRole> sysRolePage = sysRoleService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
		return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, sysRolePage.getTotal())).setData(Optional.ofNullable(sysRolePage.getRecords()).orElse(Lists.newArrayList()));
	}

	/**
	 * 查询所有角色
	 * @return VO
	 */
	@RequestMapping(value = "/select", method = RequestMethod.POST)
	@PreAuthorize("hasRole('but:role:select')")
	public R select() {
		// 查询列表数据
		QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne(StrUtil.toUnderlineCase(FieldConstant.ROLE_NAME), Constant.SUPER_ADMIN_NAME);
		queryWrapper.ne(StrUtil.toUnderlineCase(FieldConstant.ROLE_ID), Constant.PROJECT_CONTROL_ROLE);
		List<SysRole> sysRoleList = sysRoleService.list(queryWrapper);
		return R.ok().setData(Optional.ofNullable(sysRoleList).orElse(Lists.newArrayList()));
	}

	/**
	 * 角色详情
	 * @param roleId 角色id
	 * @return VO
	 */
	@RequestMapping(value = "/info/{roleId}", method = RequestMethod.GET)
	@PreAuthorize("hasRole('but:role:info')")
	public R info(@PathVariable("roleId") Long roleId) {
		SysRole role = sysRoleService.getById(roleId);
		// 查询角色对应的资源id
		List<Long> menuIdList = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().lambda()
				.eq(SysRoleMenu::getRoleId, roleId)).stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
		role.setMenuIdList(menuIdList);
		return R.ok().setData(role);
	}

	/**
	 * 保存角色
	 * @param role 角色
	 * @return VO
	 */
	@SysLog("保存角色")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@PreAuthorize("hasRole('but:role:save')")
	public R save(@Validated(SysRoleSaveGroup.class) SysRole role) {
		role.setCreator(getUserId());
		return sysRoleService.saveRole(role);
	}

	/**
	 * 更新角色
	 * @param role 角色
	 * @return VO
	 */
	@SysLog("更新角色")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@PreAuthorize("hasRole('but:role:update')")
	public R update(@Validated(SysRoleUpdateGroup.class) SysRole role) {
		role.setUpdater(getUserId());
		role.setUpdateTime(new Date());
		return sysRoleService.updateRole(role);
	}

	/**
	 * 删除角色
	 * @param roleId 角色id
	 * @return VO
	 */
	@SysLog("删除角色")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@PreAuthorize("hasRole('but:role:delete')")
	public R delete(@NotNull(message = "角色编码不能为空") Long roleId) {
		return sysRoleService.deleteRole(roleId);
	}

}
